package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.cache.prefix.UserInfoKeyPrefix;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录资源控制器
 */
@RestController
public class LoginController {
    @Reference
    private IUserInfoService userInfoService;
    @Reference
    private IUserInfoRedisService userInfoRedisService;
    /**
     * 手机号校验接口
     * @param phone 手机号
     * @return true表示未注册, false表示已注册
     */
    @RequestMapping("/checkPhone")
    public boolean checkPhone(String phone){
        return !userInfoService.checkPhone(phone);
    }

    /**
     * 注册
     * @param phone
     * @param nickname
     * @param password
     * @param rpassword
     * @param verifyCode
     * @return
     */
    @RequestMapping("/userRegist")
    public Object regist(String phone, String nickname, String password, String rpassword, String verifyCode){
        userInfoService.regist(phone, nickname, password, rpassword, verifyCode);
        return new AjaxResult();
    }

    /**
     * 登录接口
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/userLogin")
    public Object userLogin(String username, String password, HttpServletResponse resp, HttpSession session){
        String token = userInfoService.userLogin(username, password);
        //将token返回给浏览器
        CookieUtil.addCookie(resp, UserInfoKeyPrefix.USER_INFO_COOKIE_NAME, token);
        //共享session到浏览器
        session.setAttribute("userInfo", userInfoRedisService.getUserInfoByToken(UserInfoKeyPrefix.USER_INFO_TOKEN, token));
        return new AjaxResult();
    }
}
